/**
 * @Title: LeaveOutDetailActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月20日 下午10:47:24
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.R;
import com.jason.fingerprint.beans.LeaveOutBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DataHelper;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.DialogHelper;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.logic.MatchFingerprintSyncLogic;
import com.jason.fingerprint.utils.DataUtils;
import com.jason.fingerprint.widget.LoadingDialog;

import org.kymjs.aframe.database.KJDB;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: LeaveOutDetailActivity
 * @Description: 请销假详情
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月20日 下午10:47:24
 */
public class LeaveOutDetailActivity extends BaseActivity {

	private static final String TAG = "LeaveOutDetailActivity";
	private static final int INTERVAL_TIME_MINUTE = 20;//请销假间隔时间
	private static final int mChooseImageCount = 1;
    private static final long FINGER_AGAIN_TIME = 1500L;

	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;

	@BindView(id = R.id.tv_id)
	private TextView mIdTextView;
	@BindView(id = R.id.tv_name)
	private TextView mNameTextView;
	@BindView(id = R.id.tv_organId)
	private TextView mOrganIdTextView;
	@BindView(id = R.id.tv_organ)
	private TextView mOrganTextView;
	@BindView(id = R.id.tv_signType)
	private TextView mSignTypeTextView;
	@BindView(id = R.id.tv_time)
	private TextView mTimeTextView;
	@BindView(id = R.id.tv_isSick)
	private TextView mIsCancelTextView;
	@BindView(id = R.id.leave_out_detail_button_ask_leave, click = true)
	private Button mAskLeaveButton;
	@BindView(id = R.id.leave_out_detail_button_sick_leave, click = true)
	private Button mSickLeaveButton;

	@BindView(id = R.id.tv_isAsk)
	private TextView mIsAskTextView;
	@BindView(id = R.id.tv_ask_time)
	private TextView mAskTimeTextView;
	@BindView(id = R.id.tv_ask_photo)
	private TextView mAskPhotoTextView;
	@BindView(id = R.id.ask_photo_layout,click = true)
	private RelativeLayout mAskPhotoLayout;

	@BindView(id = R.id.tv_isSick)
	private TextView mIsSickTextView;
	@BindView(id = R.id.tv_sick_time)
	private TextView mSickTimeTextView;
	@BindView(id = R.id.tv_sick_photo)
	private TextView mSickPhotoTextView;
	@BindView(id = R.id.sick_photo_layout,click = true)
	private RelativeLayout mSickPhotoLayout;

	private AppContext mAppContext;
	private KJDB mKjdb;
	private LeaveOutBean mLeaveOutBean;
	private int mSignType = 1;// 默认请假签到
	private List<String> mCacheCheckImages = new ArrayList<String>();
	private MatchFingerprintSyncLogic mLogic;
	private LoadingDialog mProgressDialog;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_leave_out_detail);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		super.initWidget();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		super.initData();
		mAppContext = (AppContext) getApplicationContext();
		mKjdb = mAppContext.getKjdb();
		mProgressDialog = new LoadingDialog(this);
		Intent intent = getIntent();
		if (intent != null) {
			mLeaveOutBean = (LeaveOutBean) intent
					.getSerializableExtra("LeaveOutBean");
			Log.i(TAG,mLeaveOutBean.toString());
			String name = mLeaveOutBean.getName();
			mTitleTextView.setText(name);
			mIdTextView.setText(mLeaveOutBean.getRymcid());
			mNameTextView.setText(name);
			mOrganIdTextView.setText(mLeaveOutBean.getOrganid());
			mOrganTextView.setText(mLeaveOutBean.getOrgan());
			mSignTypeTextView.setText(DataHelper
					.getContentBySignType(mLeaveOutBean.getSignType()));
			mTimeTextView.setText(mLeaveOutBean.getTime());
			mIsSickTextView.setText(DataHelper
					.getContentByIsCancel(mLeaveOutBean.getIsCancel()));
			mIsAskTextView.setText(DataHelper
					.getContentByIsCancel(mLeaveOutBean.getSignFlag()));
			//初始化开始签到信息
			List<LeaveOutBean> askBeans = mKjdb.findAllByWhere(LeaveOutBean.class,"id = '" + mLeaveOutBean.getId() + "' and signType = '1' ");
			if (askBeans != null && !askBeans.isEmpty()){
				updateAskView(askBeans.get(0));
			}

			//初始化结束签到信息

			List<LeaveOutBean> sickBeans = mKjdb.findAllByWhere(LeaveOutBean.class,"id = '" + mLeaveOutBean.getId() + "' and signType = '3' ");
			if (sickBeans != null && !sickBeans.isEmpty()){
				updateSickView(sickBeans.get(0));
			}
		}
		initFinger();
	}

	//更新请假签到信息
	private void updateAskView(LeaveOutBean askBean){
		if (askBean != null){
			mAskTimeTextView.setText(askBean.getTime());
			final String askPhotoPath = askBean.getPhotoUrl();
			if (!TextUtils.isEmpty(askPhotoPath)){
				mAskPhotoTextView.setText("图片");
				mAskPhotoLayout.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						List<String> mCacheCheckImages = new ArrayList<String>();
						if (!StringUtils.isEmpty(askPhotoPath)) {
							mCacheCheckImages.add(askPhotoPath);
							Intent mIntent = new Intent(LeaveOutDetailActivity.this, PreviewPhotoActivity.class);
							mIntent.putStringArrayListExtra("images", (ArrayList<String>) mCacheCheckImages);
							mIntent.putExtra("position", 0);
							startActivity(mIntent);
							return;
						}
					}
				});
			}else{
				mAskPhotoTextView.setText("");
			}
		}
	}

	//更新销假签到信息
	private void updateSickView(LeaveOutBean sickBean){
		if (sickBean != null){
			mSickTimeTextView.setText(sickBean.getTime());
			final String sickPhotoPath = sickBean.getPhotoUrl();
			if (!TextUtils.isEmpty(sickPhotoPath)){
				mSickPhotoTextView.setText("图片");
				mSickPhotoLayout.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						List<String> mCacheCheckImages = new ArrayList<String>();
						if (!StringUtils.isEmpty(sickPhotoPath)) {
							mCacheCheckImages.add(sickPhotoPath);
							Intent mIntent = new Intent(LeaveOutDetailActivity.this, PreviewPhotoActivity.class);
							mIntent.putStringArrayListExtra("images", (ArrayList<String>) mCacheCheckImages);
							mIntent.putExtra("position", 0);
							startActivity(mIntent);
							return;
						}
					}
				});
			}else{
				mSickPhotoTextView.setText("");
			}
		}
	}

	// 初始化指纹信息
	private void initFinger() {
		mLogic = new MatchFingerprintSyncLogic(this);
		mLogic.setHandle(mFingerpringHandler);
		mLogic.isManager(false);
	}

	private Handler mFingerpringHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Message message = new Message();
			switch (msg.what) {
				case UIHelper.FINGERPRINT_UPCHAR_SUCCESS:
					break;
				case UIHelper.FINGERPRINT_UPCHAR_FAIL:// char--返回失败
				case UIHelper.FINGERPRINT_REGMODE_FAIL:// char--模板合成失败
				case UIHelper.FINGERPRINT_GENCHAR_FAIL:// char--生成特征值失败
				case UIHelper.FINGERPRINT_DELETECHAR_FAIL:// char--模板下载失败
				case UIHelper.FINGERPRINT_UPIMAGE_FAIL:// image--生成失败
				case UIHelper.FINGERPRINT_SEARCH_FAIL:
					message.what = 101;
					mMatchHandler.handleMessage(message);
					break;
				case UIHelper.FINGERPRINT_SEARCH_SUCCESS:
					// 匹配成功
					int pageId = msg.arg1;
					message.what = 100;
					message.arg1 = pageId;
					mMatchHandler.handleMessage(message);
					break;
				case UIHelper.FINGERPRINT_AGAIN:// 再次按手指
                    mProgressDialog.setIsOut(true);
                    mProgressDialog.setMessage("请再次按指纹...");
                    mProgressDialog.show();
                    new Handler().postDelayed(mFingerAgainRunnable, FINGER_AGAIN_TIME);
                case UIHelper.FINGERPRINT_ONMATCH_SUCCESS:// image--图片合成成功

					break;

                default:
                    break;
            }
        }

        ;

    };

    private Runnable mFingerAgainRunnable = new Runnable() {

        @Override
        public void run() {
            if (mLogic != null){
                mLogic.executeAgain();
            }
        }
    };

	// 指纹验证结果回调
	private Handler mMatchHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (mProgressDialog != null) {
				mProgressDialog.dismiss();
			}
			if (mLogic != null) {
				mLogic.destory();
			}
			switch (msg.what) {
				case 100:
					// 匹配成功
					int pageId = msg.arg1;
//					saveData(pageId);
					//判断当前指纹选择的用户和当前用户是否一致
					FingerPrintBean bean = mKjdb.findById(pageId,FingerPrintBean.class);
					if (bean != null){
						Log.i(TAG,bean.toString());
					}
					if (bean != null && bean.getType() == 1 && mLeaveOutBean != null && !TextUtils.isEmpty(bean.getUserId()) && bean.getUserId().equals(mLeaveOutBean.getRymcid())){
						choosePhoto(DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
					}else {
						Toast.makeText(LeaveOutDetailActivity.this, "没有找到匹配的指纹", Toast.LENGTH_SHORT)
								.show();
					}
					break;
				case 101:
					// 匹配失败
					takePhotoSign();
					break;

				default:
					break;
			}
		};
	};

	//进行拍照签到，选取矫正人员
	private void takePhotoSign() {
		// 拍照
		new AlertDialog.Builder(this)
				.setTitle("拍照签到")
				.setMessage("没有找到匹配的指纹,是否进行拍照签到？")
				.setCancelable(true)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						//TODO 拍照
						choosePhoto(DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK);
					}

				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				}).create().show();
	}

	// 指纹验证
	private void matchFingerPrint() {
		mProgressDialog.setMessage("请按指纹...");
		mProgressDialog.show();
		mLogic.execute();
		mProgressDialog.setMatchLogic(mLogic);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view
	 * .View)
	 */
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(this);
			break;
		case R.id.leave_out_detail_button_ask_leave:
			// TODO 没有指纹或者打卡的签到
			mSignType = 1;
//			choosePhoto();
			if (mLeaveOutBean != null){
				if (!isSuccessSign(mLeaveOutBean.getId(),mSignType)){
					matchFingerPrint();
				}
			}
			break;
		case R.id.leave_out_detail_button_sick_leave:
			// TODO 没有指纹或者打卡的签到
			mSignType = 3;
//			choosePhoto();
			if (mLeaveOutBean != null){
				if (!isSuccessSign(mLeaveOutBean.getId(),mSignType)){
					matchFingerPrint();
				}
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i(TAG, "---> onActivityResult requestCode:" + requestCode
				+ ",resultCode:" + resultCode);
		if (requestCode == DialogHelper.CHOOSE_PHOTO_REQUEST_OK && resultCode == 1001) {
			saveDate(DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					String path = mCacheCheckImages.get(0);
					Message message = new Message();
					message.what = 100;
					message.obj = path;
					savePhoto(path);
				}

			}
		}
		if (requestCode == DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK && resultCode == 1001) {
			if (data != null) {
				mCacheCheckImages = data
						.getStringArrayListExtra("mCacheCheckImages");
				// 保存图片到数据库
				if (mCacheCheckImages != null && !mCacheCheckImages.isEmpty()) {
					String path = mCacheCheckImages.get(0);
					Message message = new Message();
					message.what = 101;
					message.obj = path;
					if (saveDate(DialogHelper.CHOOSE_PHOTO_RECORD_REQUEST_OK)){
						savePhoto(path);
					}
				}

			}
		}
	}

	private Handler mSavePhotoHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 100:
				String path = (String) msg.obj;
				savePhoto(path);
				break;

			default:
				break;
			}
		};
	};

	// 把选取的图片保存到数据库
	private boolean savePhoto(String photoPath) {
		Log.i(TAG, "---> savePhoto photoPath:" + photoPath);
		Log.i(TAG, "---> savePhoto :" + mLeaveOutBean);
		if (!StringUtils.isEmpty(photoPath)) {
			ImageOrAudioBean bean = DataHelper.getImageOrAudioBeanInfoByPath(
					this, photoPath,1);
			bean.setServiceId(5);
			bean.setSignType(String.valueOf(mSignType));
			bean.setParentId(mLeaveOutBean.getId());
			Log.i(TAG, "---> savePhoto " + bean);
			mKjdb.save(bean);
			if (mSaveLeaveOutBean != null){
				mSaveLeaveOutBean.setPhotoUrl(bean.getFilePath());
				mKjdb.update(mSaveLeaveOutBean);
				if (mSignType != 1) {
					updateSickView(mSaveLeaveOutBean);
				}else{
					updateAskView(mSaveLeaveOutBean);
				}
				return true;
			}
		}
		Toast.makeText(this, "选取图片失败", Toast.LENGTH_SHORT).show();
		return false;
	}

	// 图片
	private void choosePhoto(int requestId) {
		if (mLeaveOutBean != null) {
			// TODO 弹出选择照片
//			String id = mLeaveOutBean.getId();
//			boolean flag = isSuccessSign(id, mSignType);
//			if (!flag) {
//			}
			takePhoto(requestId);
		} else {
			Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
		}
	}

	private LeaveOutBean mSaveLeaveOutBean;

	// 保存签到信息到数据库
	private boolean saveDate(int requestId) {
		if (mLeaveOutBean != null) {
			LeaveOutBean bean2 = new LeaveOutBean();
			bean2.setId(mLeaveOutBean.getId());
			bean2.setTime(DataUtils.converDatLongToString(
					System.currentTimeMillis(), DateFormat.DATE_YMD_HMS));
			if (mSignType == 1 ){
				bean2.setSignFlag("1");
			}
			bean2.setRymcid(mLeaveOutBean.getRymcid());
			bean2.setName(mLeaveOutBean.getName());
			bean2.setPhotoUrl(mLeaveOutBean.getPhotoUrl());
			bean2.setSignType(String.valueOf(mSignType));
			bean2.setIsCancel(mLeaveOutBean.getIsCancel());
			bean2.setIsCancelLeave(mLeaveOutBean.getIsCancelLeave());
			bean2.setLeaveId(mLeaveOutBean.getLeaveId());
			bean2.setOrganid(mLeaveOutBean.getOrganid());
			bean2.setOrgan(mLeaveOutBean.getOrgan());
			bean2.setState(1);
			if (requestId == DialogHelper.CHOOSE_PHOTO_REQUEST_OK){
				bean2.setRegistrationType(0);
			}else {
				bean2.setRegistrationType(1);
			}
			// 保存成功之后需要提示是否拍照
			mSaveLeaveOutBean = bean2;
			mKjdb.save(bean2);
			String tip = "请假签到成功";
			if (mSignType != 1) {
				tip = "销假签到成功";
				updateSickView(mSaveLeaveOutBean);
			}else{
				updateAskView(mSaveLeaveOutBean);
			}
			Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
			if (requestId == DialogHelper.CHOOSE_PHOTO_REQUEST_OK){
				KJActivityManager.create().finishActivity(this);
			}
			return true;
		}
		Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
		return false;
	}

	private void takePhoto(final int requestId) {
		// 拍照
		new AlertDialog.Builder(this).setTitle("拍照").setMessage("是否进行拍照？")
				.setCancelable(true)
				.setPositiveButton("确定", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent takePicture = new Intent(
								LeaveOutDetailActivity.this,
								ChoosePhotoActivity.class);
						takePicture.putExtra(
								ChoosePhotoActivity.CHOOSE_PHOTO_COUNT,
								mChooseImageCount);
						startActivityForResult(takePicture,requestId);
					}

				}).setNegativeButton("取消", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (requestId == DialogHelper.CHOOSE_PHOTO_REQUEST_OK){
							saveDate(DialogHelper.CHOOSE_PHOTO_REQUEST_OK);
						}
						dialog.dismiss();
					}

				}).create().show();

	}

	// 判断是否签到过
	private boolean isSuccessSign(String id, int signType) {
		try {
			List<LeaveOutBean> beans = mKjdb.findAllByWhere(LeaveOutBean.class,
					" signType = '" + signType + "' and id = '" + id + "'");
			if (beans != null && !beans.isEmpty()) {
				LeaveOutBean bean = beans.get(0);
				if (bean != null) {
					String toast = "";
					if (signType == 1) {
						toast = "已经请假签到";
					} else if (signType == 3) {
						toast = "已经销假签到";
					}
					Toast.makeText(this, toast, Toast.LENGTH_SHORT).show();
					return true;

				}
			}else{
				if (signType == 3){
					List<LeaveOutBean> outBeans = mKjdb.findAllByWhere(LeaveOutBean.class,
							" signType = '" + 1 + "' and id = '" + id + "'");
					if (outBeans != null && !outBeans.isEmpty()){
						LeaveOutBean outBean = outBeans.get(0);
						if (outBean != null){
							String time = outBean.getTime();
							if (!TextUtils.isEmpty(time)){
								long t = DataUtils.convertStrToLong(time,DateFormat.DATE_YMD_HMS);
								long min = (System.currentTimeMillis() - t) / (60 * 1000);
								if (min < INTERVAL_TIME_MINUTE){
									Toast.makeText(this,"请在" + (INTERVAL_TIME_MINUTE - min) + "分钟后，结束签到",Toast.LENGTH_SHORT).show();
									return true;
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

}
